package com.zazu.mycl.application.terminal;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.beans.PropertyVetoException;
import java.util.logging.Level;

import javax.swing.JTextArea;
import javax.swing.text.BadLocationException;

import com.zazu.mycl.application.ApplicationController;
import com.zazu.mycl.application.CommandRunner;
import com.zazu.mycl.application.DefaultCommandRunner;

public class MyClInputKeyHandler implements KeyListener {

	MyClInputKeyHandler(CommandRunner cr)
	{
		this.cr = cr;
	}
	
	public void keyPressed(KeyEvent selKey) {

		JTextArea ta = (JTextArea) selKey.getSource();
	
		int caretPosition = ta.getCaretPosition();
		
		int lastline = ta.getLineCount()-1;
		
		int keyCode = selKey.getKeyCode();
		
		
		
		//If the caret is in the last line, allow edits
		try {
			
			if(caretPosition == ta.getLineStartOffset(lastline))
			{
				if(keyCode == KeyEvent.VK_DELETE || keyCode == KeyEvent.VK_BACK_SPACE || keyCode == KeyEvent.VK_LEFT)
				{
					selKey.consume();
					ApplicationController.logger.log(Level.INFO, "Consuming Key, key not allowed at this point.");
				}
				else if(keyCode == KeyEvent.VK_UP)
				{
					//Up Pressed
					selKey.consume();
					cr.upPressed();
					ApplicationController.logger.log(Level.INFO, "Consuming Up Key.");
				}
				else if(keyCode == KeyEvent.VK_DOWN)
				{
					//Up Pressed
					selKey.consume();
					cr.downPressed();
					ApplicationController.logger.log(Level.INFO, "Consuming Down Key.");
				}
			}
			else if(caretPosition >= ta.getLineStartOffset(lastline) && caretPosition <= ta.getLineEndOffset(lastline))
			{
				if(keyCode == KeyEvent.VK_UP)
				{
					//Up pressed
					selKey.consume();
					cr.upPressed();
					ApplicationController.logger.log(Level.INFO, "Consuming Up Key.");
				}
				if(keyCode == KeyEvent.VK_DOWN)
				{
					//Up pressed
					selKey.consume();
					cr.downPressed();
					ApplicationController.logger.log(Level.INFO, "Consuming Down Key.");
				}
				else if(keyCode == KeyEvent.VK_ENTER)
				{
					//Enter Pressed
					selKey.consume();
					cr.EnterPressed();
				}
			}
			else
			{
				selKey.consume();
				
				//Put the caret to the last line
				ta.setCaretPosition(ta.getText().length());
				
				ApplicationController.logger.log(Level.INFO, "Change Vetoed.");
			}
		} catch (BadLocationException e) {
			//Cancel the key typed
			ApplicationController.logger.log(Level.SEVERE, "Bad location exception when checking input validity.");
			
			selKey.consume();
		}	
		
		
	}

	public void keyReleased(KeyEvent selKey) {
		
		
		
	}

	public void keyTyped(KeyEvent selKey) {
		
		
		
	}

	private CommandRunner cr;
}
